package com.py.credit.controller;

import com.alibaba.fastjson.JSON;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.GatewayUserEntity;
import com.py.credit.service.GatewayAuthenticationService;
import com.py.credit.service.UserReportService;
import com.py.credit.service.XypjRemoteBaseService;
import com.py.credit.utils.UuidUtil;
import com.py.framework.core.helper.HttpServletHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Company: WWW.xypy.com.cn
 * @ClassName UserReportController
 * @Description: 用户申报接口
 * @Params:
 * @Author: YaoS
 * @Create: 2018-10-22 15:23
 **/
@RestController
@RequestMapping(value = "/xypj/gateway")
public class UserReportController {

    private static final String TYPE_C = "C";
    private static final String TYPE_D = "D";
    @Autowired
    private UserReportService userReportService;

    @Autowired
    private XypjRemoteBaseService xypjRemoteBaseService;

    @Autowired
    private GatewayAuthenticationService gatewayAuthenticationService;

    /**
     * 根据库id返回系统归集侧边栏信息
     * 已完成
     *
     * @param rootId
     * @return RestServiceResult
     * @author YaoS
     * @date 20:32 18/10/29
     **/
    @RequestMapping(value = "/selectLeftTable.json")
    public RestServiceResult<List<Map<String, Object>>> selectLeftTable(
            @RequestParam(value = "rootId", defaultValue = "", required = true) String rootId,
            @RequestParam(value = "tybm", defaultValue = "", required = true) String tybm,
            HttpServletRequest request) {
        RestServiceResult result = new RestServiceResult<>();
        String tableList = "";
        try {
            //根据传入参数返回系统归集侧边栏表单数据表名
            tableList = userReportService.selectLeftTable(rootId);
            //调用远程接口获取侧边栏元数据
            if (tableList == null || tableList.isEmpty()) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("当前用户暂未配置可填报的数据，请联系管理员！");
            } else {
                RestServiceResult<List<Map<String, Object>>> rs = xypjRemoteBaseService.selectLeftTable(tableList, tybm);
                if (rs == null) {
                    result.setMsg("未查出系统归集表数据！");
                    result.setCode(RestServiceResult.CODE_UNKNOW);
                    return result;
                } else if (RestServiceResult.CODE_SUCCESS != rs.getCode()) {
                    return result;
                }
                result.setData(rs.getData());
            }
            return result;
        } catch (Exception e) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("查询企业列表信息异常！");
            ExceptionLogger.error("查询企业列表信息异常！", e.getMessage(), e);
            return result;
        }
    }

    /**
     * 保存当前用户等待校验的表记录数并插入KV表
     *
     * @param dataList  提交的kv表
     * @param tableId   表的id
     * @param tableName 表名
     * @param tybm      统一编码
     * @param type      提交类型:I新增,U修改,D删除
     * @param recordId  编辑修改记录的Id
     * @param dataId    要删除的数据的id值
     * @return RestServiceResult
     * @author YaoS
     * @date 20:32 18/10/29
     **/
    @RequestMapping(value = "/insertRecordList.json")
    public RestServiceResult<List<Map<String, Object>>> saveRecordList(
            @RequestParam(value = "dataList", defaultValue = "", required = true) String dataList,
            @RequestParam(value = "tableId", defaultValue = "", required = true) String tableId,
            @RequestParam(value = "tableName", defaultValue = "", required = true) String tableName,
            @RequestParam(value = "tybm", defaultValue = "", required = true) String tybm,
            @RequestParam(value = "type", defaultValue = "", required = true) String type,
            @RequestParam(value = "recordId", defaultValue = "", required = true) String recordId,
            @RequestParam(value = "dataId", defaultValue = "", required = true) String dataId,
            @RequestParam(value = "chinaName", defaultValue = "", required = true) String chinaName,
            HttpServletRequest request) {

        RestServiceResult result = new RestServiceResult<>();
        GatewayUserEntity user = new GatewayUserEntity();
        String token = HttpServletHelper.getUserXypjGatewayToken(request);
        try {
            user = gatewayAuthenticationService.getCurrentUserInfo(token);
        } catch (Exception e) {
            com.py.framework.core.log.ExceptionLogger.error("UserReportController#checkTable", "未获取到当前用户信息！");
        }


        String key = "";
        String value = "";
        String codeName = "";
        String uuid = UuidUtil.getUUid();
        ArrayList<HashMap<String, String>> list = JSON.parseObject(dataList, ArrayList.class);
        if (!TYPE_D.equals(type)) {
            String data = xypjRemoteBaseService.checkTable(dataList, tableId);
            if (data != null) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg(data);
                return result;
            }
        }
        try {
            //将数据计入record表
            userReportService.saveTableForRecord(uuid, tybm, type, tableName, tableId, dataId, chinaName);

            for (Map<String, String> map : list) {
                key = map.get("key");
                value = String.valueOf(map.get("value"));
                codeName = map.get("codeName");
                userReportService.saveTableForRecordDetail(key, value, uuid, codeName);
            }

            return result;
        } catch (Exception e) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("新增当前用户等待校验的表记录数并插入KV表！");
            ExceptionLogger.error("新增当前用户等待校验的表记录数并插入KV表！", e.getMessage(), e);
            return result;
        }
    }

    /**
     * 取消record表
     *
     * @param id
     * @return RestServiceResult
     * @author YaoS
     * @date 10:10 18/10/31
     **/
    @RequestMapping(value = "/operateRecord.json")
    public RestServiceResult<List<Map<String, Object>>> operateRecord(
            @RequestParam(value = "id", defaultValue = "", required = true) String id) {
        RestServiceResult result = new RestServiceResult<>();
        try {
            userReportService.delRecord(id);
            return result;
        } catch (Exception e) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("撤销record表异常！");
            ExceptionLogger.error("撤销record表异常！", e.getMessage(), e);
            return result;
        }
    }

    /**
     * 查询当前用户等待审核的表记录
     *
     * @param tybm
     * @param tableId
     * @return RestServiceResult
     * @author YaoS
     * @date 20:32 18/10/29
     **/
    @RequestMapping(value = "/selectRecordList.json")
    public RestServiceResult<List<Map<String, Object>>> selectRecordList(
            @RequestParam(value = "tybm", defaultValue = "", required = true) String tybm,
            @RequestParam(value = "tableId", defaultValue = "", required = true) String tableId,
            HttpServletRequest request) {
        RestServiceResult result = new RestServiceResult<>();
        try {
            List<Map<String, Object>> list = userReportService.selectRecordList(tybm, tableId);
            result.setData(list);
            return result;
        } catch (Exception e) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("查询表信息列表信息异常！");
            ExceptionLogger.error("查询企业列表信息异常！", e.getMessage(), e);
            return result;
        }
    }

    /**
     * 提交表单
     *
     * @param tybm
     * @param tableId
     * @return RestServiceResult
     * @author YaoS
     * @date 16:16 18/10/31
     **/
    @RequestMapping(value = "/commitTableList.json")
    public RestServiceResult<List<Map<String, Object>>> commitTableList(
            @RequestParam(value = "tybm", defaultValue = "", required = true) String tybm,
            @RequestParam(value = "tableId", defaultValue = "", required = true) String tableId,
            HttpServletRequest request) {
        RestServiceResult result = new RestServiceResult<>();
        GatewayUserEntity user = new GatewayUserEntity();
        String token = HttpServletHelper.getUserXypjGatewayToken(request);
        try {
            user = gatewayAuthenticationService.getCurrentUserInfo(token);
        } catch (Exception e) {
            ExceptionLogger.error("UserReportController#checkTable", "未获取到当前用户信息！");
        }
        try {
            //判断法人库自然人库
            String type = (TYPE_C.equals(user.getType())) ? "100000" : "100001";
            //提交当前用户所有表单
            userReportService.commitTableList(tybm, tableId, user.getId() + "", user.getZtmc() + "", type);
            return result;
        } catch (Exception e) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("提交表单异常！");
            ExceptionLogger.error("提交表单异常！", e.getMessage(), e);
            return result;
        }
    }

    /**
     * 单表提交直接审核
     *
     * @param tybm
     * @param tableId
     * @return RestServiceResult
     * @author YaoS
     * @date 11:05 18/11/2
     **/
    @RequestMapping(value = "/commitOneTable.json")
    public RestServiceResult<List<Map<String, Object>>> commitOneTable(
            @RequestParam(value = "dataList", defaultValue = "", required = true) String dataList,
            @RequestParam(value = "tableId", defaultValue = "", required = true) String tableId,
            @RequestParam(value = "tableName", defaultValue = "", required = true) String tableName,
            @RequestParam(value = "tybm", defaultValue = "", required = true) String tybm,
            @RequestParam(value = "type", defaultValue = "", required = true) String type,
            @RequestParam(value = "recordId", defaultValue = "", required = true) String recordId,
            @RequestParam(value = "dataId", defaultValue = "", required = true) String dataId,
            @RequestParam(value = "chinaName", defaultValue = "", required = true) String chinaName,
            HttpServletRequest request) {

        RestServiceResult result = new RestServiceResult<>();
        String data = xypjRemoteBaseService.checkTable(dataList, tableId);
        if (data != null) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg(data);
            return result;
        }
        GatewayUserEntity user = new GatewayUserEntity();
        String token = HttpServletHelper.getUserXypjGatewayToken(request);
        String key = "";
        String value = "";
        String codeName = "";
        ArrayList<HashMap<String, Object>> list = JSON.parseObject(dataList, ArrayList.class);
        try {
            user = gatewayAuthenticationService.getCurrentUserInfo(token);
            String uuid = UuidUtil.getUUid();
            userReportService.saveTableForRecord(uuid, tybm, "U", tableName, tableId, dataId, chinaName);
            for (Map map : list) {
                key = (String) map.get("key");
                value = String.valueOf(map.get("value"));
                codeName = (String) map.get("codeName");
                userReportService.saveTableForRecordDetail(key, value, uuid, codeName);
            }
            //提交当前用户当前的所有表单
            String utype = (TYPE_C.equals(user.getType())) ? "100000" : "100001";
            userReportService.commitTableList(tybm, tableId, user.getId() + "", user.getZtmc() + "", utype);
            return result;
        } catch (Exception e) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("单表提交表单异常！");
            ExceptionLogger.error("单表提交表单异常！", e.getMessage(), e);
            return result;
        }
    }

    /**
     * 编辑记录
     *
     * @param recordId 记录主键id
     * @param dataList 编辑的json数据
     * @return
     * @author YaoS
     * @date 16:16 18/10/31
     **/
    @RequestMapping(value = "/editorRecord.json")
    public RestServiceResult<List<Map<String, Object>>> editorRecord(
            @RequestParam(value = "recordId", defaultValue = "", required = true) String recordId,
            @RequestParam(value = "tableId", defaultValue = "", required = true) String tableId,
            @RequestParam(value = "dataList", defaultValue = "", required = true) String dataList) {
        RestServiceResult result = new RestServiceResult<>();
        String data = xypjRemoteBaseService.checkTable(dataList, tableId);
        if (data != null) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg(data);
            return result;
        }
        try {
            userReportService.editorRecord(recordId, dataList);
            return result;
        } catch (Exception e) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("提交表单异常！");
            ExceptionLogger.error("提交表单异常！", e.getMessage(), e);
            return result;
        }
    }

    /**
     * 查看表数据是否在审核中
     *
     * @param tybm       登录用户的统一编码
     * @param resourceId 表名
     * @return
     * @author YaoS
     * @date 16:16 18/10/31
     **/
    @RequestMapping(value = "/checkTableAudit.json")
    public RestServiceResult<List<Map<String, Object>>> checkTableAudit(
            @RequestParam(value = "tybm", defaultValue = "", required = true) String tybm,
            @RequestParam(value = "resourceId", defaultValue = "", required = true) String resourceId
    ) {
        RestServiceResult result = new RestServiceResult<>();
        if (userReportService.checkTableAudit(tybm, resourceId) > 0) {
            result.setData("Y");
        } else {
            result.setData("N");
        }
        return result;
    }

}
